﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using Web.SystemConfig.Services;
using System.Data;
using Microsoft.Practices.Unity;
using ePlanet.ArchiveMange.Services;
using ePlanet.ArchiveMange.Models;
using DreamBuilder.Core.Message;
using DreamBuilder.Core.Container;
using ePlanet.ArchiveMange.Enum;

namespace Web.Views.ArchiveManage
{
    public partial class PageFileEdit : PageBase
    {
        #region 属性变量
        [Dependency]
        public ICodeTable CodeTableService
        {
            get;
            set;
        }

        [Dependency]
        public IArchiveMenuService ArchiveMenuService
        {
            get;
            set;
        }

        [Dependency]
        public IPageFileService PageFile
        {
            get;
            set;
        }

        [Dependency]
        public IAuth_Org orgService
        {
            get;
            set;
        }

        public string archiveTypeName;

        /// <summary>
        /// 卷内件ID
        /// </summary>
        public string DataID
        {
            get
            {
                if (Request.QueryString["DataID"] != null)
                {
                    ViewState["DataID"] = Request.QueryString["DataID"];
                }
                if (ViewState["DataID"] != null)
                {
                    return ViewState["DataID"].ToString();
                }
                else
                {
                    ViewState["DataID"] = Guid.NewGuid().ToString();
                    return ViewState["DataID"].ToString();
                }
            }
        }

        /// <summary>
        /// 卷ID
        /// </summary>
        public string ArchiveId
        {
            get
            {
                if (Request.QueryString["archiveId"] != null)
                {
                    ViewState["archiveId"] = Request.QueryString["archiveId"];
                }
                if (ViewState["archiveId"] != null)
                {
                    return ViewState["archiveId"].ToString();
                }
                else
                {
                    return string.Empty;
                }
            }
        }
        /// <summary>
        /// 档案类型
        /// </summary>
        public string ReqArchiveType
        {
            get
            {
                if (this.Request.QueryString["archiveType"] != null)
                {
                    return this.Request.QueryString["archiveType"];
                }
                else
                {
                    throw new Exception("档案类型不能为空");
                }
            }
        }

        /// <summary>
        /// 卷的档号
        /// </summary>
        public string ArchiveNum
        {
            get
            {
                if (this.Request.QueryString["archiveNum"] != null)
                {
                    return this.Request.QueryString["archiveNum"];
                }
                else
                {
                    return string.Empty;
                }
            }
        }

        public int AddOrderNum
        {
            get
            {
                if (ViewState["AddOrderNum"] == null)
                {
                    ViewState["AddOrderNum"] = 1;
                }
                return int.Parse(ViewState["AddOrderNum"].ToString());
            }
            set
            {
                ViewState["AddOrderNum"] = value;
            }
        }
        #endregion

        #region 页面初始化
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.attachArchive.ObjectID = DataID;
                this.attachArchive.ObjectTableName = "";
                AddAttachmentInfos();
                InitControls();
                LoadData();
                SetButtonVisable();
            }
            SetControlVisable();
            archiveTypeName = this.h_archiveTypeName.Value;
            SetButtonVisible();
        }

        private void SetButtonVisible()
        {
            if (!string.IsNullOrEmpty(Request.QueryString["op"]) && Request.QueryString["op"].Equals("scan"))
            {
                btnAddArchiveBack.Visible = false;
                btnAddArchive.Visible = false;
            }
        }

        /// <summary>
        /// 初始化数据项
        /// </summary>
        private void InitControls()
        {
            //初始化附件上传控件
            this.attachArchive.ObjectID = DataID;
            DataSet KeepTime = CodeTableService.GetCodeTableDataByType("KeepTime");
            if (KeepTime != null && KeepTime.Tables.Count > 0)
            {
                this.ddlKeepTime.DataSource = KeepTime;
                this.ddlKeepTime.DataTextField = "Code_Desc";
                this.ddlKeepTime.DataValueField = "CodeTableID";
                this.ddlKeepTime.DataBind();
                this.ddlKeepTime.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }
            DataSet CarrierType = CodeTableService.GetCodeTableDataByType("CarrierType");
            if (CarrierType != null && CarrierType.Tables.Count > 0)
            {
                this.ddlCarrierType.DataSource = CarrierType;
                this.ddlCarrierType.DataTextField = "Code_Desc";
                this.ddlCarrierType.DataValueField = "CodeTableID";
                this.ddlCarrierType.DataBind();
                this.ddlCarrierType.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }

            DataSet SecurityData = CodeTableService.GetCodeTableDataByType("SecurityType");
            if (SecurityData != null && SecurityData.Tables.Count > 0)
            {
                this.ddlSecurity.DataSource = SecurityData;
                this.ddlSecurity.DataTextField = "Code_Desc";
                this.ddlSecurity.DataValueField = "CodeTableID";
                this.ddlSecurity.DataBind();
                this.ddlSecurity.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }
            //保密期限ddlKeepSecurityTime
            DataSet KeepSecurityTimeData = CodeTableService.GetCodeTableDataByType("KeepSecurityTime");
            if (KeepSecurityTimeData != null && KeepSecurityTimeData.Tables.Count > 0)
            {
                this.ddlKeepSecurityTime.DataSource = KeepSecurityTimeData;
                this.ddlKeepSecurityTime.DataTextField = "Code_Desc";
                this.ddlKeepSecurityTime.DataValueField = "CodeTableID";
                this.ddlKeepSecurityTime.DataBind();
                this.ddlKeepSecurityTime.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }

            //年度（会计类特有）
            //int year = DateTime.Now.Year;
            //for (int i = year - 10; i < year + 10; i++)
            //{
            //    this.ddlYear.Items.Add(new ListItem("--" + i + "--", i.ToString()));
            //}
            //this.ddlYear.Items.Insert(0, new ListItem("--请选择--", "-1"));

            ArchiveMangeModal.ARCHIVEMENUDataTable dtArchiveMenu = ArchiveMenuService.GetArchiveMenuById(ReqArchiveType);
            ArchiveMangeModal.ARCHIVEMENURow row =  (dtArchiveMenu.Rows[0] as ArchiveMangeModal.ARCHIVEMENURow);
            if (dtArchiveMenu != null && dtArchiveMenu.Rows.Count > 0)
            {
                this.txtArchiveType.Text = row.TYPECODE;
                this.h_ArchiveTypeId.Value = row.TYPEID.ToString();
                this.h_archiveTypeName.Value = row.ARCHIVEMENU;
            }
            //来源
            this.txtArchiveSource.Text = "在线录入__档案整理";
            this.txtFileOrgName.Text = this.CurrentUser.Org_Name;
            this.txtArchiveNum.Text = ArchiveNum;
            this.txtBoxNum.Text = "未装盒";
            this.txtFullFondsNum.Text = this.CurrentUser.Org_FullFondsNum;
            this.h_FileOrgID.Value = this.CurrentUser.ORG_ID;

            this.txtArchiveNum.Enabled = false;
            this.txtArchiveSource.Enabled = false;
            this.txtFullFondsNum.Enabled = false;
            this.txtArchiveType.Enabled = false;

            this.h_ArchiveTypeId.Value = ReqArchiveType;
            //如果是修改，保存并录入不显示
            if (Request.QueryString["DataID"] != null)
            {
                this.btnAddArchive.Visible = false;
            }

        }
        /// <summary>
        /// 设置输入控件的可见性
        /// </summary>
        private void SetControlVisable()
        {
           int type =-1;
            if(!int.TryParse(this.ReqArchiveType,out type))
            {
                Alert("档案类型有误");
            }
            int baseType = ArchiveMenuService.GetArchiveBaseIDById(type);
            switch (baseType)
            {
                //如果是科研类
                case ((int)ArchiveBaseType.Technology):
                    DivYear.Visible = false;
                    DivTypeNum.Visible = false;
                    DivPubLisher.Visible = true;
                    DivHujianhao.Visible = true;
                    DivDocumentNum.Visible = true;
                    break;
                //如果是设备类
                case ((int)ArchiveBaseType.Equipment):
                    DivYear.Visible = false;
                    DivTypeNum.Visible = true;
                    DivPubLisher.Visible = true;
                    DivHujianhao.Visible = false;
                    DivDocumentNum.Visible = false;
                    break;
                //如果是基建类
                case ((int)ArchiveBaseType.BulidProject):
                    DivYear.Visible = false;
                    DivTypeNum.Visible = false;
                    DivPubLisher.Visible = true;
                    DivHujianhao.Visible = false;
                    DivDocumentNum.Visible = true;
                    break;
                //如果是会计类
                case ((int)ArchiveBaseType.Account):
                    DivYear.Visible = true;
                    DivTypeNum.Visible = false;
                    DivPubLisher.Visible = false;
                    DivHujianhao.Visible = false;
                    DivDocumentNum.Visible = false;
                    break;
                //默认，全部都隐藏
                default:
                    DivYear.Visible = false;
                    DivTypeNum.Visible = false;
                    DivPubLisher.Visible = false;
                    DivHujianhao.Visible = false;
                    DivDocumentNum.Visible = false;
                    break;
            }
          
        }

        /// <summary>
        /// 设置按钮可用性
        /// </summary>
        private void SetButtonVisable()
        {
            if (Request.QueryString["ReadOnly"] != null)
            {
                this.btnAddArchive.Visible = false;
                this.btnAddArchiveBack.Visible = false;
            }
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        private void LoadData()
        {
            IPageFileService DocumentArchiveService = UContainer.Resolve<IPageFileService>();
            ArchiveMangeModal.PAGEFILEDataTable dt = DocumentArchiveService.GetAllDocumenArchivetDataById(this.DataID);
             if (dt.Rows.Count > 0)
             {
                 this.CurrentPageState = PageState.State_Edit;

                 ArchiveMangeModal.PAGEFILERow row = dt.Rows[0] as ArchiveMangeModal.PAGEFILERow;
                 this.txtArchiveNum.Text = row.ARCHIVENUM;
                 this.txtArchiveSource.Text = row.ARCHIVESOURCE;
                 ArchiveMangeModal.ARCHIVEMENUDataTable dtMenu = ArchiveMenuService.GetArchiveMenuById(row.ARCHIVETYPE.ToString());
                 ArchiveMangeModal.ARCHIVEMENURow drMenu = dtMenu.Rows[0] as ArchiveMangeModal.ARCHIVEMENURow;
                 this.txtArchiveType.Text = drMenu.ARCHIVEMENU;
                 this.h_ArchiveTypeId.Value = row.ARCHIVETYPE.ToString();
                 this.txtBoxNum.Text = row.BOXNUM;
                 //DataTable dtOrg = orgService.GetORGInfo(row.FILEORGID);
                 //this.txtFileOrgName.Text = dtOrg.Rows[0]["Org_Name"].ToString();
                 //this.h_FileOrgID.Value = row.FILEORGID;
                 //归档单位改为直接明文了
                 this.txtFileOrgName.Text = row.FILEORGID;
                 this.txtFullFondsNum.Text = row.FULLFONDSNUM;
                 this.txtPageNum.Text = row.PAGENUM.ToString();
                 this.txtPublishTime.Text = row.IsPUBLISHTIMENull() ? "" : row.PUBLISHTIME.ToString("yyyy-MM-dd");
                 this.txtTempOrderNum.Text = row.TEMPORDERNUM;
                 this.txtTitle.Text = row.TITLE;
                 this.ddlCarrierType.SelectedValue = row.F_CARRIERTYPE;
                 this.ddlKeepTime.SelectedValue = row.F_KEEPTIME;
                 this.ddlSecurity.SelectedValue = row.F_SECURITYTYPE;

                 //对卷内件不同的值进行处理-----------------------------
                 this.txtPublisher.Text=row.PUBLISHER;//责任者，除会计类之外都有
                  this.txtDocumentNum.Text=row.DOCUMENTNUM;//文件编号，科研类特有
                  this.txtHujianhao.Text=row.HUJIANHAO;//互见号，科研类特有
                 this.txtTypeNum.Text=row.TYPENUM ;//型号，设备类特有
                 this.ddlYear.Text=row.F_YEAR;//年度，会计类特有
                 this.ddlKeepSecurityTime.SelectedValue = row.F_KEEPSECURITYTIME;

             }
        }

        /// <summary>
        /// 附件实体增加更多信息
        /// </summary>
        private void AddAttachmentInfos()
        {
            Hashtable addInfos = new Hashtable();
            addInfos.Add("FunctionID", "0"); //功能ID(1：发文文档 2：发文附件 3：收文文档 4：收文附件 5：即时消息附件 6：新闻附件)
            addInfos.Add("FileTypeID", ""); //附件文件夹类型
            addInfos.Add("FileURL", ""); //附件存储路径
            addInfos.Add("IsXml", "0"); //是否XML代码化
            addInfos.Add("CreateUserID", this.CurrentUser.User_ID); //用户ID 目前可以写个固定的值作为测试
            addInfos.Add("Remark", "即时消息附件"); //备注
            if (Session["AddInfos"] == null)
            {
                Session.Add("AddInfos", addInfos);
            }
            else
            {
                Session.Remove("AddInfos");
                Session.Add("AddInfos", addInfos);
            }
        }
        #endregion

        #region 按钮事件
        /// <summary>
        /// 保存并继续录入按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAddArchive_Click(object sender, EventArgs e)
        {
            string msg = string.Empty;
            int statusId = 0;
            SaveData(out msg, out statusId);
            if (!string.IsNullOrEmpty(msg))
            {
                Alert(msg);
                //this.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "$(function(){ window.location=window.location;});", true);
                ViewState.Remove("HasFileList");
                ViewState.Remove("DataID");
                this.attachArchive.ObjectID = DataID;
                this.attachArchive.ObjectTableName = "";
                this.attachArchive.Refresh = true;
                this.attachArchive.ReFreshload();
                AddAttachmentInfos();
                //InitControls();
                //LoadData();
            }
        }

        /// <summary>
        /// 保存并返回按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAddArchiveBack_Click(object sender, EventArgs e)
        {
            string msg = string.Empty;
            int statusId = 0;
            SaveData(out msg, out statusId);
            //GoBack();
            if (!string.IsNullOrEmpty(msg))
            {
                CloseWindow(msg, statusId);
            }
        }

        /// <summary>
        /// 返回按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnBack_Click(object sender, EventArgs e)
        {
            CloseWindow("页面关闭，刷新父页面", 0);
        }
        #endregion

        #region 页面方法
        /// <summary>
        /// 保存按钮事件(返回状态消息,状态值)
        /// 
        /// </summary>
        /// <param name="msg"></param>
        private void SaveData(out string msg,out int statusId)
        {
            msg = string.Empty;
            statusId = 0;
            IPageFileService PageFileService = UContainer.Resolve<IPageFileService>();
            if (string.IsNullOrEmpty(this.txtTitle.Text.Trim()))
            {
                Alert("标题不能为空!");
                return;
            }
            if (this.DivPubLisher.Visible == true && string.IsNullOrEmpty(this.txtPublisher.Text.Trim()))
            {
                Alert("责任人不能为空!");
                return;
            }
            DateTime o_time = new DateTime();
            if (string.IsNullOrEmpty(this.txtPublishTime.Text.Trim()) || !DateTime.TryParse(this.txtPublishTime.Text.Trim(), out o_time))
            {
                Alert("文件日期不能为空!");
                return;
            }
            if (string.IsNullOrEmpty(this.txtPageNum.Text))
            {
                Alert("页号不能为空!");
                return;
            }

            //if (!string.IsNullOrEmpty(this.txtDoplicateBodyNum.Text.Trim()) && !int.TryParse(this.txtDoplicateBodyNum.Text.Trim(), out s_out))
            //{
            //    Alert("副本数量输入格式不正确!");
            //    return;
            //}
            //if (!string.IsNullOrEmpty(this.txtMainBodyNum.Text.Trim()) && !int.TryParse(this.txtMainBodyNum.Text.Trim(), out s_out))
            //{
            //    Alert("正文输入格式不正确!");
            //    return;
            //}
            if (this.ddlCarrierType.SelectedIndex < 1)
            {
                Alert("载体类型不能为空!");
                return;
            }
            if (this.ddlKeepTime.SelectedIndex < 1)
            {
                Alert("保管期限不能为空!");
                return;
            }
            if (this.ddlSecurity.SelectedIndex < 1)
            {
                Alert("密级不能为空!");
                return;
            }
             string message = string.Empty;
            if(!VelidateInteger(this.ddlYear.Text,out message))
            {
                Alert("年度格式不正确，应该为正确的年份数，如：2014");
            }
            DataSet ds = new DataSet();
            ArchiveMangeModal.PAGEFILEDataTable dtDocumentArchive = new ArchiveMangeModal.PAGEFILEDataTable();
            ArchiveMangeModal.PAGEFILERow row = dtDocumentArchive.NewPAGEFILERow();
            row.DATAID = this.DataID;
            if (!string.IsNullOrEmpty(ArchiveId))
            {
                row.F_ARCHIVEID = ArchiveId; //新增卷内件如果传了卷的ID，则保存，否则，这个值为空
            }
            else
            {
                row.SetF_ARCHIVEIDNull();//如果是还没建立卷，则卷id 为null
            }
            row.ARCHIVESOURCE = this.txtArchiveSource.Text;
            //档案类型取隐藏域中的值
            row.ARCHIVETYPE = Convert.ToInt32(this.h_ArchiveTypeId.Value);
            row.ARCHIVENUM = this.txtArchiveNum.Text;
            if (this.txtBoxNum.Text == "未装盒")
            {
                row.BOXNUM = null;
            }
            else
            {
                row.BOXNUM = this.txtBoxNum.Text;
            }
            row.CREATETIME = DateTime.Now;
            row.CREATEUSERID = this.CurrentUser.User_ID;
            if (CurrentPageState == PageState.State_New)
            {
                row.SetLASTUPDATETIMENull();
                row.SetLASTUPDATEUSERNull();
            }
            else
            {
                row.LASTUPDATETIME = DateTime.Now;
                row.LASTUPDATEUSER = this.CurrentUser.User_ID;
            }
            row.F_KEEPTIME = this.ddlKeepTime.SelectedValue;
            row.F_CARRIERTYPE = this.ddlCarrierType.SelectedValue;
            row.F_SECURITYTYPE = this.ddlSecurity.SelectedValue;

            //添加保密期限限制(1为无密级) Start--------------------------
            if (this.ddlSecurity.SelectedIndex > 1)
            {
                if (this.ddlKeepSecurityTime.SelectedIndex == 0)
                {
                    Alert("当前密级级别必须选择保密期限");
                    return;
                }
                else
                {
                    row.F_KEEPSECURITYTIME = this.ddlKeepSecurityTime.SelectedValue;
                }
            }
            else
            {
                row.SetF_KEEPSECURITYTIMENull();
            }
            //添加保密期限限制(1为无密级)   END---------------------------
            //获取最大的序号+1
            row.ORDERNUM = PageFile.GetPageFileMaxOrder(this.ArchiveId)+1;
            //row.FILEORGID = this.h_FileOrgID.Value;
            //归档单位改为明文了
            row.FILEORGID = this.txtFileOrgName.Text;
            row.FULLFONDSNUM = this.txtFullFondsNum.Text;
            row.EXPANSIONINFO = null;
            row.PAGENUM = this.txtPageNum.Text.Trim();
            row.TITLE = this.txtTitle.Text;
            row.PUBLISHTIME = Convert.ToDateTime(this.txtPublishTime.Text);
            row.TEMPORDERNUM = this.txtTempOrderNum.Text;

            //对卷内件不同的值进行处理-----------------------------
            row.PUBLISHER = this.txtPublisher.Text;//责任者，除会计类之外都有
            row.DOCUMENTNUM = this.txtDocumentNum.Text;//文件编号，科研类特有
            row.HUJIANHAO = this.txtHujianhao.Text;//互见号，科研类特有
            row.TYPENUM = this.txtTypeNum.Text;//型号，设备类特有
            row.F_YEAR = this.ddlYear.Text;//年度，会计类特有

            dtDocumentArchive.NewRow();
            dtDocumentArchive.Rows.Add(row);
            if (this.CurrentPageState == PageState.State_Edit)
            {
                dtDocumentArchive.AcceptChanges();
                row.SetModified();
            }
            ds.Tables.Add(dtDocumentArchive);
            try
            {
                bool bResult = PageFileService.SaveData(ds);
                bResult = SaveAttachment() & bResult;
                if (bResult)
                {
                    Hashtable ht = null;
                    if (Session["ArchivePageFile"] is Hashtable)
                    {
                        ht = (Hashtable)Session["ArchivePageFile"];
                    }
                    else
                    {
                        ht = new Hashtable();
                    }
                    ht.Add(DataID, ReqArchiveType);
                    Session["ArchivePageFile"] = ht;
                    WriteUserLog("用户" + CurrentUser.User_Name + "添加了"+archiveTypeName+"类型卷的标题为" + row.TITLE + "的卷内件", OracleLogType.ArchiveManage);
                    msg = "保存成功";
                    statusId = 1;
                }
            }
            catch (Exception ex)
            {
                //Alert("保存失败,错误信息:"+ex.Message);
                msg = "保存失败,错误信息:" + ex.Message;
            }
        }

        private bool SaveAttachment()
        {
            DataTable dt_Attach = this.attachArchive.GetSaveDataTable(this.attachArchive.ObjectID, this.attachArchive.ObjectTableName);
            IPageFileService DocumentArchiveService = UContainer.Resolve<IPageFileService>();
           return DocumentArchiveService.SaveAttach(dt_Attach, this.attachArchive.ObjectTableName, this.attachArchive.ObjectID,
                this.attachArchive.AttachmentDBHelperString);
        }

        /// <summary>
        /// 返回
        /// </summary>
        private void GoBack()
        {
            //this.Response.Redirect("DocumentArchiveList.aspx?archiveType="+ReqArchiveType);
            this.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "window.close();", true);
        }

        /// <summary>
        /// 关闭当前页面
        /// <param name="msg">提示消息</param>
        /// <param name="statusId">状态值，判断是否成功</param>
        /// </summary>
        private void CloseWindow(string msg,int statusId)
        {
            this.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "closePage('"+msg+"',"+statusId+");", true);
        }
        #endregion
    }
}